package com.code.generator.cn.util.fb;

import com.alibaba.fastjson.JSON;
import com.code.generator.cn.entity.CoderField;
import com.code.generator.cn.entity.CoderTable;
import com.code.generator.cn.util.MyFileUtil;
import com.code.generator.cn.util.PathUtil;
import com.code.generator.cn.util.base.CommonUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
public class FbEntityUtil {

    /**
     * 生成对应的entity
     * @param coderTable
     * @param coderFields
     * @param configuration
     * @param uploadPath
     */
    public static void createEntity(CoderTable coderTable, List<CoderField> coderFields, Configuration configuration, String uploadPath) throws IOException, TemplateException {
        Template temp=configuration.getTemplate("/fb/entity.ftl");
        Writer file =null;

        //获取包名
        String packageName  = PathUtil.getCreateBasePath(coderTable);



        String groupPath=packageName.replace(".","/");
        //生成entity的路径
        String entityPath=uploadPath+"/src/main/java/"+groupPath+"/entity/";
        //设置生成的路径
        MyFileUtil.createFileDir(entityPath);
        //设置生成的属性
        Map<String,Object> createMap=new HashMap<>();
        //设置实体对象要生成的包名
        createMap.put("packageName",packageName);
        //设置实体对象的类名
        String className=coderTable.getModifyName();
        createMap.put("className",className);

        //设置字段属性
        List<Map<String,Object>> fieldList=new ArrayList<>();
        for (CoderField coderField : coderFields) {
            Map<String, Object> fieldMap = CommonUtil.createFieldMap(coderField,createMap);
            fieldList.add(fieldMap);
        }
        if(!createMap.containsKey("DATEIMPORT")){
            createMap.put("DATEIMPORT","");
        }
        createMap.put("fieldList",fieldList);
        //设置生成的文件名
        file = new FileWriter(entityPath+className+".java");
        temp.process(createMap, file);
        log.info(JSON.toJSONString(createMap));
        file.close();

    }
}
